package cn.acewill.yxd.yunxundian.ui.user;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.componet.CircleImageView;
import cn.acewill.yxd.yunxundian.componet.photoCrop.BitmapUtils;
import cn.acewill.yxd.yunxundian.componet.photoCrop.PopupUtil;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.departBean;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

import static cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver.whetherConnectNetWork;


/**
 * Created by XXX on 2017/4/3.
 */
public class PersonActivity extends BaseActivity implements View.OnClickListener{

    /*拍照权限标识*/
    public static final int MY_PERMISSIONS_REQUEST_CALL = 0x50;
    /*本地数据操作*/
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    /*用户id*/
    private int userId;
    /*用户头像*/
    private CircleImageView userPhoto;
    /*昵称，英文名，部门，职位*/
    private TextView otherName,englishName,department,userPost;

    /*用户最终提交到后台的图片的路径*/
    private String resultFilePath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTitleBar("个人信息");
        setContentView(R.layout.user_person_info);
        super.onCreate(savedInstanceState);
        /*初始化图片的路径*/
        initView();
        try {
           localSearchData();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    public void initView(){
        this.userId= MainActivity.id;
        Button sureBtn = (Button) findViewById(R.id.sureBtn);
        sureBtn.setVisibility(View.GONE);
        this.otherName= (TextView) findViewById(R.id.otherName);
        this.englishName= (TextView) findViewById(R.id.englishName);
        this.department= (TextView) findViewById(R.id.department);
        this.userPost= (TextView) findViewById(R.id.userPost);
        this.userPhoto= (CircleImageView) findViewById(R.id.userPhoto);
        RelativeLayout rePhoto = (RelativeLayout) findViewById(R.id.RePhoto);
        rePhoto.setOnClickListener(this);
        RelativeLayout reotherName = (RelativeLayout) findViewById(R.id.ReotherName);
        reotherName.setOnClickListener(this);
        RelativeLayout reEnglishName = (RelativeLayout) findViewById(R.id.ReEnglishName);
        reEnglishName.setOnClickListener(this);
        RelativeLayout reDepart = (RelativeLayout) findViewById(R.id.ReDepart);
        reDepart.setOnClickListener(this);
        RelativeLayout rePost = (RelativeLayout) findViewById(R.id.RePost);
        rePost.setOnClickListener(this);
        RelativeLayout reMdPass = (RelativeLayout) findViewById(R.id.ReMdPass);
        reMdPass.setOnClickListener(this);
        try {
            localSearchData();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.RePhoto:
                if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_CALL);
                }else{
                    //文件存储的路径
                    if(whetherConnectNetWork==1){
                        showPop();
                    }
                    else{
                        showAnimaDialog(PersonActivity.this,"当前无网络连接，请在有网络连接时使用");
                    }
                }
                break;
            case R.id.ReotherName:
                if (whetherConnectNetWork==1){
                    startActivityForResult(new Intent(this,ModifiUserInfoActivity.class).putExtra("type",0),0);
                }else{
                    showAnimaDialog(PersonActivity.this,"当前无网络连接，请在有网络连接时使用");
                }
                break;
            case R.id.ReEnglishName:
                if (whetherConnectNetWork==1){
                    startActivityForResult(new Intent(this,ModifiUserInfoActivity.class).putExtra("type",1),1);
                }
                break;
            case R.id.ReDepart:
            case R.id.RePost:
                showAnimaDialog(PersonActivity.this,"暂不开放");
                break;
            case R.id.ReMdPass:
                if (whetherConnectNetWork==1){
                    startActivity(new Intent(this,ModifiUserInfoActivity.class).putExtra("type",2));
                }
                else{
                showAnimaDialog(PersonActivity.this,"当前无网络连接，请在有网络连接时使用");
            }
                break;
        }
    }

    public void localSearchData() throws DbException {
        Employee emps=db.selector(Employee.class).where("ID","=",userId).findFirst();
        otherName.setText(emps.getFirstName());
        englishName.setText(emps.getLastName());
        int depatr=emps.getDepartmentId();
        departBean dp= db.selector(departBean.class).where("ID","=",depatr+"").findFirst();
        if (TextUtils.isEmpty(emps.getEmpImage())){
            userPhoto.setImageResource(R.mipmap.icon_logo);
        }else{
            String path= pubClass.pictureSavePath+emps.getEmpImage();
            Glide.with(this).load(path).skipMemoryCache(true).into(userPhoto);
        }

        if(dp!=null){
            department.setText(dp.getDepartmentName());
        }else{
            department.setText("尚未分配部门");
        }

        CommonMapBean role=db.selector(CommonMapBean.class).where("ServerId","=", emps.getID()).and("cmType","=","role").findFirst();
        if(role!=null){
            userPost.setText(role.getCmValue());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       switch (requestCode){
           case 0:
               if(data!=null){
                   otherName.setText(data.getStringExtra("otherName"));
               }
               break;
           case 1:
               if(data!=null){
                   englishName.setText(data.getStringExtra("eName"));
               }
               break;
       }
    }



    /*无权限时则申请拍照的权限*/
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==MY_PERMISSIONS_REQUEST_CALL){
            if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
                showPop();
            }else{
                showAnimaDialog(PersonActivity.this,"您禁止了拍照权限，可在手机管家中打开");
            }
        }
    }


    public void downloadFile(String url, String path) {

        final RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path);
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }
            @Override
            public void onStarted() {

            }
            @Override
            public void onLoading(long total, long current, boolean isDownloading) {

            }
            @Override
            public void onSuccess(File result) {
                String thispath=result.getAbsolutePath();
                Glide.with(PersonActivity.this).load(thispath).placeholder(R.mipmap.icon_stub).signature(new StringSignature("version")).into(userPhoto);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                Toast.makeText(PersonActivity.this,"用户头像加载失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {

            }
        });
    }


    //showPop
    boolean isMultiSelector=false;
    Dialog popDialog;
    final int REQUEST_CODE_GALLERY=1000;
    final  int REQUEST_CODE_CARMEAR=1001;

    public void showPop(){
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View holder = inflater.inflate(R.layout.view_popup_button,
                null, false);
        View gallery = holder.findViewById(R.id.btnPhoto);
        View capture = holder.findViewById(R.id.btnCapture);
        View cancel = holder.findViewById(R.id.btnCanel);

        ButtonClick click = new ButtonClick();
        gallery.setOnClickListener(click);// 图库选择
        capture.setOnClickListener(click);// 拍照选择
        cancel.setOnClickListener(click);// 取消
        popDialog= PopupUtil.makePopup(this,holder);
        popDialog.show();
    }
    public class ButtonClick implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            YXDAPP.GallerySet(1,PersonActivity.this);
            if (popDialog!=null){
                popDialog.dismiss();
            }
            if (v.getId() == R.id.btnPhoto) {// 图库选取
                if (isMultiSelector){
                    GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY,YXDAPP.functionConfig,myResultCallBack);
                }else{ //选取头像
                    GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY,YXDAPP.functionConfig,myResultCallBack);
                }
            }

            if (v.getId() == R.id.btnCapture) {// 拍照
                // 从相册选取
                GalleryFinal.openCamera(REQUEST_CODE_CARMEAR,YXDAPP.functionConfig,myResultCallBack);
            }
            if (v.getId()==R.id.btn_cancel){
                popDialog.dismiss();
            }
        }
    }


    GalleryFinal.OnHanlderResultCallback myResultCallBack =new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(final int reqeustCode, final List<PhotoInfo> resultList) {
            //拿到图片后压缩处理保存
            Thread t = new Thread(String.valueOf(Looper.getMainLooper())) {
                @Override
                public void run() {
                    for (int i = 0; i < resultList.size(); i++) {

                        String path = resultList.get(i).getPhotoPath();
                        WindowManager winManager = getWindowManager();
                        DisplayMetrics metrics = new DisplayMetrics();
                        winManager.getDefaultDisplay().getMetrics(metrics);
                        Bitmap mBitmap = BitmapUtils.getBmpFromFile(path,
                                metrics.widthPixels, metrics.heightPixels, null);

                        checkPhotoPathExist();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        Random random = new Random();
                        String fileName2 = String.valueOf(random.nextInt(Integer.MAX_VALUE));
                        String newPhotoName = "yxd" + sdf.format(new Date()) + fileName2+"userPhoto";
                        resultFilePath =  pubClass.pictureSavePath + newPhotoName + ".jpg";
                        //流保存
                        File file = new File(resultFilePath);
                        FileOutputStream outputStream = null;
                        try {
                            outputStream = new FileOutputStream(file);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        mBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);

                        try {
                            outputStream.flush();
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //保存图片后发送广播通知更新数据库
                        Uri uri = Uri.fromFile(file);
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

                        Message msg=new Message();
                        msg.what=0;
                        myhandler.sendMessage(msg);

                    }
                }

            };
            t.start();
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(PersonActivity.this,errorMsg,Toast.LENGTH_SHORT).show();
        }
    };
    /**
     * 判断目录是否存在，不存在则创建改文件夹
     */
    public void checkPhotoPathExist() {

        File file = new File( pubClass.pictureSavePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler myhandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==0){
                //此处处理请求的逻辑
                uploadPhoto();
            }
        }
    };

    public void uploadPhoto(){
        Map<String, Object> map = new HashMap<>();
        File file = new File(resultFilePath);
        map.put("task", "setUserUpLoadAvatar");
        map.put("empid", MainActivity.id);
        map.put("uploadfile", file);

        pubClass.UpLoadFile(pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                String[] array = result.split("\\|");
                if (array[0].equals("200")) {
                    showAnimaDialog(PersonActivity.this,"头像修改成功");
                    AsynData data = new AsynData(null);
                    try {
                        data.asynEmployeeDatax(MainActivity.id);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Glide.with(PersonActivity.this).load(resultFilePath).into(userPhoto);
                    Intent in = new Intent();
                    in.putExtra("filePath", resultFilePath);
                    setResult(1, in);
                } else {
                    showAnimaDialog(PersonActivity.this,"头像修改失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            finish();
        }
        return super.onKeyDown(keyCode, event);

    }
}
